/**
 *	This contains code that allows a player to choose or create a game 
 *	on the server to play.
**/

var GameChooser = {
	
	init: function() {
		var header = this._header = document.getElementById("GCheader")
		this._gameListObj = document.getElementById("GameList")
		this._loadingAnim = document.getElementById("GCloadingAnim")
		
		//create name input box
		var nh = this._nameHolder = document.createElement("input")
		nh.type = "text"
		nh.placeholder = "your name"
		nh.value = "doug"											//temp!!!!!
		nh.width = 30
		header.appendChild(nh)
		
		//create search button
		var sb = this._searchButton = document.createElement("input")
		sb.type = "button"
		sb.value = "search"
		sb.onclick = this._joinHost("searchButton")
		header.appendChild(sb)
		
		//create host button
		var hb = this._hostButton = document.createElement("input")
		hb.type = "button"
		hb.value = "host"
		hb.onclick = this._joinHost("hostButton")
		header.appendChild(hb)
		
		//create cancel button
		var cb = this._cancelButton = document.createElement("input")
		cb.type = "button"
		cb.value = "cancel"
		cb.disabled = "disabled"
		cb.onclick = this._clickCancel()
		header.appendChild(cb)
	},
	
	_joinHost: function(type) {
		var that = this
		return function() {
			//check that the user has input a name
			if (!that._nameHolder.value) {
				alert("please type in a user name to join games")
				return
			}
			
			//disable the header and enable the 'cancel' button
			that.enableHeader("disable")
			
			
			//on searchButton click event, get list of existing games
			if (type === "searchButton") {
				API.gamesList(function(response) {
					GameChooser.createGamesList(response, "search")
				})
			
			//on hostButton click event, create a new game and display it
			} else if (type === "hostButton") {
				API.createGame(
					{ playerName: that._nameHolder.value },
					function(response) {
						var mygame = JSON.parse(response),
							gameList = { games: [ mygame ] }
						GameChooser.createGamesList(gameList, "host")
						GameChooser.hostMainLoop("start", mygame)
					}
				)
			}

		}  //end return function
	},
	
	_clickCancel: function() {
		var that = this
		return function() {
			that.hostMainLoop("stop")										//cancel the loop which searches for your partner
			that.createGamesList("clear")									//clear the list
			that.enableHeader("enable")										//re-enable the header!
		}
	},
	
	//enables and disables the header
	enableHeader: function(type) {
		var enableType = ( type === "disable" ? "disabled" : "" ),
			enableReverse = ( type === "disable" ? "" : "disabled" )
		
		this._nameHolder.disabled = enableType
		this._searchButton.disabled = enableType
		this._hostButton.disabled = enableType
		this._cancelButton.disabled = enableReverse
	},
	
	//creates a list of games as returned by the server
	createGamesList: function(response, listType) {
		//clear list in the DOM
		var listobj = this._gameListObj
		while (listobj.hasChildNodes()) {
			listobj.removeChild(listobj.firstChild)
		}
	
		//get the list
		var gamesList
		if (response === "clear") {
			return														//just exit if 'clear' list was called
		} else if (typeof response === "string") {
			gamesList = JSON.parse(response).games
		} else {
			gamesList = response.games
		}
		
		this._gamesList = gamesList										//save list for later
				
		//create the list in the DOM
		var l
		for (var i=0, ii=gamesList.length; i<ii; i++) {
			l = gamesList[i]
			
			var li = document.createElement("li")
			
			var p = document.createElement("p")
			p.className = "labels"
			p.innerHTML = "gameId: <br/>players: <br/><br/>winner: "
			li.appendChild(p)
			
			var p = document.createElement("p")
			p.innerHTML = [	l.gameId, l.players[0], l.players[1], l.winner ].join("<br/>")
			li.appendChild(p)
			
			if (listType === "search") {								//only have click through if this is a search list
				li.onclick = this._clickMaker(i)	
			}
			listobj.appendChild(li)
		}
	},
	
	_clickMaker: function(gameno) {
		var that = this
		return function() {
			//join the game on the server
			API.joinGame(
				{
					gameId: that._gamesList[gameno].gameId,
					playerName: that._nameHolder.value
				},
				function(payload) {
					var newGame = JSON.parse(payload),
						playerName = that._nameHolder.value
					that.beginGame(newGame, playerName)				//init the board and begin playing!
				}
			)
		}
	},
	
	
	beginGame: function(newGame, playerName) {		
		Game.setUpGame(newGame, playerName)							//set up game
		Main.TabBar.clickTab(1)										//go to game!
	},
	
	
	//this checks the status of the game we are hosting.
	//serves 2 functions:
	//	-	check in with the server, so it knows we are actively waiting, 
	//		and does not delete the game.
	//	-	check if the game has matched us with an opponent yet!
	hostMainLoop: function(action, gameInfo) {
		var that = this
		if (action === "start") {
			//begin loading animation
			this._loadingAnim.style.display = "block"
			
			//move to send to the server
			var move = { gameId: gameInfo.gameId }
			
			//run this callback on successful return
			var callback = function(payload) {
				var newGame = JSON.parse(payload)
				if (newGame.players.length === 2) {					//if 2 players have joined, we're ready to go!
					GameChooser.hostMainLoop("stop")
					var playerName = that._nameHolder.value			//remember the player name for later
					GameChooser.beginGame(newGame, playerName)
				}
			}
			
			//set up the interval
			this._hostCheckInterval = setInterval(function() {
				API.checkGameStatus( move, callback )
				console.log("checking for opponent...")
			}, 1000)
		
		} else if (action === "stop") {
			//clear the interval loop, if it exists
			if (this._hostCheckInterval) {
				clearInterval(this._hostCheckInterval)
			}
			
			//end loading animation
			this._loadingAnim.style.display = "none"
		}
	}
	
}